<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="common/header :: head"></head>
<style rel="stylesheet" type="text/css">
  #right {
    float: right;
  }
  .el-form {
    margin-left: 0px !important;
  }
  .el-dialog {
    padding: 0px 20px !important;
  }
  /*证明照片样式*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .el-upload--text {
    margin-left: 40px;
    margin-top: 20px;
  }

  .clas-detail {
    display: flex;
    justify-content: space-around;
  }

  #attendence_table .el-table td, .el-table th {
    padding: 4px 0;
  }

  .el-table .qingjie-row {
    background: #87CEFA;
  }

  .el-table .chidao-row {
    background: #F5DEB3;
  }

  .el-table .zaotuo-row {
    background: #F0E68C;
  }

  .el-table .kuangke-row {
    background: #FF6347;
  }
</style>
<body>
<div id="app">
  <template>
    <el-dialog title="上传考勤表" :visible.sync="sedialogFormVisible" width="45%" height="110%">
      <el-form style="display: inline-block;margin-left: 30px">
        <el-upload class="upload-demo" ref="upload" multiple accept=".xls,.xlsx"
                   action="" :auto-upload="false" :show-file-list="true" :on-error="errorUp"
                   :before-upload="beforeUpload" :http-request="uploadFile">
          <el-button size="small" slot="trigger" type="primary">选择文件</el-button>
          <div slot="tip" style="color: red;">请上传文件大小不超过2MB,格式为 .xls类型的文件</div>
        </el-upload>
        <div style="display: flex;margin-top: 10px">
          <span style="width: 50px;height: 40px;line-height: 40px;">备注</span>
          <el-input size="small" v-model="notes" placeholder="考勤备注"></el-input>
        </div>
      </el-form>
      <p style="margin-top: 10px;">请先下载模板文件填写再上传，且一次只能上传一个文件。</p>
      <!--备注-->
      <div slot="footer" class="dialog-footer" style="display: flex">
        <el-button size="small" type="primary" @click="submitUploadList">确 定</el-button>
        <el-button size="small" @click="sedialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--编辑对话框-->
    <el-dialog title="考勤信息" top="3%" width="50%" :visible.sync="dialogTableVisible">
      <div class="clas-detail">
        <span style="color: #00ff80">已到 {{ statusNums[0] }}</span>
        <span style="color: #87CEFA">请假 {{ statusNums[1] }}</span>
        <span style="color: #F5DEB3">迟到 {{ statusNums[2] }}</span>
        <span style="color: #F0E68C">早退 {{ statusNums[3] }}</span>
        <span style="color: #FF6347">旷课 {{ statusNums[4] }}</span>
      </div>
      <div id="attendence_table">
        <el-table ref="multipleTable" v-loading="loading" :data="historyContent.list"
                  tooltip-effect="dark" :row-class-name="tableRowClassName" style="width: 100%;border: 1px">
          <el-table-column fixed min-width="20%" label="班级" align="center" prop="cname"></el-table-column>
          <el-table-column fixed min-width="20%" label="学生名称" align="center" prop="stuname"></el-table-column>
          <el-table-column prop="stuid" label="学号" min-width="20%" align="center"></el-table-column>
          <el-table-column prop="status" label="考勤状态" width="100">
            <template slot-scope="scope">
              <el-select size="mini" v-model="scope.row.status" v-if="user.identity === 3 || user.identity === 1"
                         @change="updateStatus(scope.row)" style="width: 75px">
                <el-option v-for="(status,index) in statuses" :key="index" :label="status" :value="status">
                </el-option>
              </el-select>
              <span v-else :style="{'color':scope.row.status.split(' ')[1]}">
                {{ scope.row.status.split(" ")[0] }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-top: 10px;">
          <span class="demonstration"></span>
          <el-pagination
              @current-change="handleCurrentChange1"
              layout="total, prev, pager, next, jumper"
              :current-page="currentPage1"
              :page-size="pageSize"
              :total="historyContent.total"
              :pager-count="5" align="center">
          </el-pagination>
        </div>
      </div>

    </el-dialog>

    <div>
      <div style="display: flex">
        <div style="width: 100%">
          <el-row>
            <el-col :span="3">
              <!--专业-->
              <el-select size="small" style="width: 140px;" v-model="selectContent.selectMajor" placeholder="专业"
                         @change="selectedChange">
                <el-option label="" value="全部"></el-option>
                <el-option v-for="(major,index) in majors" :key="index" :label="major" :value="major"></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <!--年级选择-->
              <el-select size="small" style="width: 140px;" v-model="selectContent.selectYear" placeholder="年级"
                         @change="selectedChange">
                <el-option label="" value="全部"></el-option>
                <el-option v-for="(year,index) in years" :key="index" :label="year" :value="year"></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <!--周次-->
              <el-select size="small" style="width: 140px;" v-model="selectContent.selectWeek" placeholder="周次"
                         @change="selectedChange">
                <el-option label="" value="全部"></el-option>
                <el-option v-for="(week,index) in 25" :key="index" :label="'第' + week + '周'" :value="week">{{
                    week
                  }}
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <!--上课老师-->
              <el-select size="small" style="width: 190px;" v-model="selectContent.selectTeacher"
                         v-if="user.identity === 1" placeholder="上课老师" @change="selectedChange">
                <el-option label="" value="全部"></el-option>
                <el-option v-for="(tea,index) in teachers" :key="index" :label="tea" :value="tea"></el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <!--课程-->
              <el-select size="small" style="width: 240px;" v-model="selectContent.selectCourse" placeholder="课程"
                         v-if="user.identity !== 2" @change="selectedChange">
                <el-option label="" value="全部"></el-option>
                <el-option v-for="(course,index) in courses" :key="index" :label="course" :value="course"></el-option>
              </el-select>
            </el-col>
            <el-col :span="3">
              <!--状态-->
              <el-select size="small" style="width: 140px;" v-model="selectContent.selectStatus" placeholder="考勤状态"
                         @change="selectedChange">
                <el-option v-for="(sta,index) in status" :key="index" :label="sta" :value="sta">
                </el-option>
              </el-select>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px;">
            <el-col :span="2">
              <el-button size="small" style="margin-right: 10px;" type="primary" @click="search">查询考勤</el-button>
            </el-col>
            <el-col :span="6">
              <span v-if="user.identity !== 2">
                <el-button size="small" type="info" @click="download">批量下载考勤表</el-button>
                <el-button size="small" type="warning" @click="[sedialogFormVisible = true]">上传考勤信息</el-button>
              </span>
            </el-col>
          </el-row>
        </div>
      </div>


      <div style="margin-top: -15px;">
        <el-divider></el-divider>
      </div>
      <el-table ref="multipleTable" v-loading="loading" :data="tableData.list" tooltip-effect="dark"
                style="width: 99%;border: 1px;margin: 0 auto;margin-top: -15px;" :row-key="getRowKeys"
                @selection-change="handleSelectionChange">
        <el-table-column fixed min-width="20%" label="课程" align="center" prop="coursename"></el-table-column>
        <el-table-column fixed width="130px" label="教室" align="center" prop="classroom"></el-table-column>
        <el-table-column prop="cname" label="班级" width="100px" align="center"></el-table-column>
        <el-table-column prop="week" label="周次" width="100px" align="center">
          <template slot-scope="scope">
            <span>第{{ scope.row.week }}周</span>
          </template>
        </el-table-column>
        <el-table-column label="上课时间" width="150px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.classtime.includes('~')">第{{ scope.row.classtime }}大节</span>
            <span v-else>第{{ scope.row.classtime }}小节</span>
          </template>
        </el-table-column>
        <el-table-column prop="date" width="150px" label="日期" align="center"></el-table-column>
        <el-table-column prop="weekStr" label="星期" width="80"></el-table-column>
        <el-table-column prop="nickname" label="上课老师" min-width="20%" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" width="120px" align="center" :reserve-selection="true">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="edit(scope.row)" v-if="scope.row.status === '1'">详情
            </el-button>
            <el-checkbox @change="addExcel(scope.row.cid,$event)" v-else>选择</el-checkbox>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="margin-top: 10px;">
        <span class="demonstration"></span>
        <el-pagination
            @current-change="handleCurrentChange"
            layout="total, prev, pager, next, jumper"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="tableData.total"
            :pager-count="5"
            align="center">
        </el-pagination>
      </div>
    </div>
  </template>
</div>


<script type="text/javascript">
  let urlBase = "../attendance/"
  var v = new Vue({
    el: "#app",
    data: {
      currentPage: 1, //当前页码
      total: '',      //总条数，后面会换成动态的
      pageSize: 10, 	//每页的总条数
      currentPage1: 1, //当前页码
      total1: '',      //总条数，后面会换成动态的
      tableData: [{
        tid: '',
        tname: ''
      }],//表单值
      // 页面加载效果
      loading: false,
      sedialogFormVisible: false,
      //考勤版
      //当前登录的用户
      user: {},

      //选择框
      //年级
      years: [],

      //专业
      majors: [],

      //上课老师
      teachers: [],

      //课程
      courses: [],

      //考勤状态
      status: ['已考勤', '未考勤'],

      //选择的班级
      selectContent: {
        //选择的年级
        selectYear: '',
        //选择的专业
        selectMajor: '',
        //选择的班级
        selectClass: '',
        //选择的周次
        selectWeek: '',
        //选择的课程
        selectCourse: '',
        //选择的老师
        selectTeacher: '',
        //选择的考勤状态
        selectStatus: ''
      },
      //多选生成excel表的信息
      excels: [],
      //证明照片地址
      imageUrl: '',
      //备注
      notes: '',
      //考勤信息编辑可见性
      dialogTableVisible: false,
      //所选择查看的班级考勤信息
      historyContent: [],
      //选择查看考勤信息
      selectCid: '',
      //所有的考勤状态
      statuses: ['已到', '请假', '迟到', '早退', '旷课'],
      //各个考勤情况的数量  依次是已到，请假，迟到，早退，旷课
      statusNums: [],
      //是否选择新的选项
      isChooseNew: false
    },
    methods: {
      // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
      getRowKeys(row) {
        return row.id
      },
      // 列表选择,val选中的表格行数据
      handleSelectionChange(value) {
      },
      //显示管理界面
      showAll: function () {
        this.$data.loading = true;
        this.getAllSelectInfo()

        this.search()
      },
      //得到所有的下拉框信息
      getAllSelectInfo() {
        //根据登录进来的用户的权限给相对于的页面展示以及相关的选项
        //年级 and 专业
        axios.get("../classInfo/getSelectInfo?teacherId=" + this.user.id).then(response => {
          if (response.data.code === 1) {
            //年级
            this.years = response.data.data.years
            //专业
            this.majors = response.data.data.majors
          } else {
            this.$message({message: response.data.msg, type: 'warning'});
          }
          this.$data.loading = false;
        })

        if (this.user.identity === 1 || this.user.identity === 2) {
          //上课老师
          axios.get("../api/user/getTeachers").then(response => {
            if (response.data.code === 1) {
              var teas = response.data.data
              for (let i = 0; i < teas.length; i++) {
                this.teachers.push(teas[i].nickname)
              }
            } else {
              this.$message({message: response.data.msg, type: 'warning'});
            }
          })
        }
        //得到所有的课程
        axios.get("../attendance/courses?teacherId=" + this.user.id).then(res => {
          if (res.data.code === 1) {
            this.courses = res.data.data
          } else {
            this.$message({message: response.data.msg, type: 'warning'});
          }
        })
      },
      // 当前页改变时触发 跳转其他页
      handleCurrentChange: function (val) {
        this.currentPage = val;
        this.showAll()
      },
      // 当前页改变时触发 跳转其他页
      handleCurrentChange1: function (val) {
        this.currentPage1 = val;
        this.showHis()
      },
      //历史考勤信息分页
      showHis() {
        this.$data.loading = true;
        this.getAllSelectInfo()

        axios.get(urlBase + "searchHistory", {
          params: {
            pageNum: this.currentPage1,
            pageSize: this.pageSize,
            sid: this.selectCid
          }
        }).then(res => {
          if (res.data.code) {
            this.historyContent = res.data.data
          } else {
            this.$message({message: "系统异常", type: "error"});
          }
        })
      },
      exportClass() {
        let data = location.href.split("/")
        let actionUrl = data[0] + "//" + data[2] + "/" + data[3] + "/classInfo/download";
        window.open(actionUrl);
      },
      //before-upload 上传文件前
      beforeUpload: function (file) {
        if (['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].indexOf(file.type) === -1 && ['application/vnd.ms-excel'].indexOf(file.type) == -1) {
          this.$message.error({message: "请上传.xlsx和.xls格式的文件", type: 'error'});
          return false;
        }
      },
      //上传失败调用
      errorUp: function (err) {
        this.$message({message: err, type: "error"})
      },
      //上传成功调用
      endUpload: function () {
        this.excels = []
        this.selectContent.selectStatus = '已考勤'
        this.search()
        //清空输入的内容
        this.notes = ''
      },
      // 解析模板
      async uploadFile(param) {
        const File = param.file;
        const service = axios.create({})
        let formData = new FormData()
        formData.append("file", File)
        //备注
        formData.append("notes", this.notes)
        //图片
        formData.append("image", this.notes)
        this.$message({message: "数据添加中请稍后!", type: "warning"});
        const res = await service({
          url: urlBase + 'upload',
          method: 'POST',
          transformRequest: [function (data, headers) {
            // 去除post请求默认的Content-Type
            delete headers.post['Content-Type']
            return data
          }],
          data: formData
        }).then(res => {
          if (res.data.code === 1) {
            this.showAll();
            this.sedialogFormVisible = false;
            this.endUpload()
            this.$message({message: '上传成功', type: "success"});
          } else {
            this.$message({message: res.data.msg, type: "error"});
          }
        })
      },
      //根据条件查询考勤内容
      search() {
        if(this.isChooseNew){
          this.currentPage = 1
          this.isChooseNew = false
        }
        var status = this.selectContent.selectStatus === '未考勤' ? 0 : 1;

        var major = this.selectContent.selectMajor === '全部' ? '' : this.selectContent.selectMajor
        //获得下拉框中改变的值
        var year = this.selectContent.selectYear === '全部' ? '' : this.selectContent.selectYear
        var week = this.selectContent.selectWeek === '全部' ? '' : this.selectContent.selectWeek
        var teacher = this.selectContent.selectTeacher === '全部' ? '' : this.selectContent.selectTeacher
        var course = this.selectContent.selectCourse === '全部' ? '' : this.selectContent.selectCourse
        axios.get("../attendance", {
          params: {
            cname: major + year,
            week: week,
            nickname: teacher,
            coursename: course,
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            status: status
          }
        }).then(res => {
          if (res.data.code === 1) {
            //操作成功
            this.tableData = res.data.data
          } else {
            this.$message({message: res.data.msg, type: "error"});
          }
        })
      },
      //上传考勤记录
      //提交后跳转到:http-request
      submitUploadList: function () {
        const files = this.$refs.upload.uploadFiles[0];

        let size2M = files.size / 1024 / 1024 < 2;
        if (!size2M) {
          this.$message.warning('上传大小不能超过2M!');
          return false;
        }

        if (files >= 0) {
          this.$message({message: "请选择文件后再点确定", type: "warning"})
        } else {
          this.$refs.upload.submit()
        }
      },
      //增加生成考勤表中的信息
      addExcel(cid, row) {
        if (row) {
          this.excels.push(cid)
        } else {
          this.excels = this.excels.filter(ele => {
            return ele !== cid
          })
        }
      },
      //下载考勤表
      download() {
        //先判断是否选择了要下载的考勤表
        if (this.excels.length === 0) {
          return this.$message({message: "请选择需要下载的考勤表", type: "warning"})
        }
        var data = '['
        this.excels.forEach(excel => {
          data += (excel + ",")
        })
        data += ']'
        // 创建一个<a>标签，设置下载链接，并触发点击事件
        var link = document.createElement("a");
        link.href = "../attendance/exportContent?excels=" + data;
        link.download = "考勤表.xlsx"; // 设置默认的文件名
        link.click();
        this.$message({message: "下载中，请稍后!", type: "success"});
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //编辑或者查看详情
      edit(row) {
        this.selectCid = row.cid
        //先判断该考勤是否考勤完成，如果还没有考勤或者在考勤当中就提示用户还没有考勤信息
        if (row.status === '1') {
          this.searchHistory(row.cid)
          this.currentPage1 = 1;
          this.dialogTableVisible = true;
        } else {
          this.$message({message: "该班级还未考勤，故没有考勤信息", type: "warnning"});
        }
      },
      //查看考勤历史信息
      searchHistory(cid) {
        axios.get(urlBase + "searchHistory", {params: {sid: cid}}).then(res => {
          if (res.data.code) {
            this.historyContent = res.data.data
            //并且查询各个考勤信息的数量
            this.statusNums = res.data.data.statusNums
          } else {
            this.$message({message: "系统异常", type: "error"});
          }
        })
      },
      //修改考勤状态
      updateStatus(row) {
        axios.get(urlBase + "updateStatus", {
          params: {
            arid: row.arid,
            status: row.status
          }
        }).then(res => {
          if (res) {
            this.$message({message: "修改成功", type: "success"});
          } else {
            this.$message({message: "系统异常", type: "error"});
          }
        })
      }, tableRowClassName({row, rowIndex}) {
        return row.style;
      }, selectedChange() {
        this.isChooseNew = true
      }
    },
    created() {
      var user = JSON.parse(sessionStorage.user);
      this.user = user
      axios.all([this.showAll()]);
    }
  })
</script>
</body>
</html>